package com.xiaogao.security.interceptor;

import com.xiaogao.common.exception.BusinessException;
import com.xiaogao.common.utils.RedisUtils;
import com.xiaogao.common.utils.token.JwtUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * 登录拦截器
 */
@Slf4j
public class LoginInterceptor implements HandlerInterceptor {
    private final RedisUtils redisUtils;

    public LoginInterceptor(RedisUtils redisUtils) {
        this.redisUtils = redisUtils;
    }

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        String uri = request.getRequestURI();
        log.info("进入拦截器------------------{}",uri);

        if (!uri.equals("/login")) { // 除了登录接口，其他都需要进行token校验
            String token = request.getHeader("token");
            // 1、token有没有传
            if (token == null) {
                throw new BusinessException(2001, "用户未登录！");
            }
            // 2、解析token是否合法
            Claims claims = JwtUtils.parse(token);

            // 3、判断token是否有效
            String key = String.valueOf(claims.get("username")).concat(":token");
            Object valueObj = redisUtils.get(key);
            if (valueObj == null) {
                throw new BusinessException(2002, "用户长时间未操作！请重新登录！");
            }

            // 4、用户的每一个操作都为token进行续签
            redisUtils.set(key, token, 60 * 60 * 2);
        }
        return true;
    }
}
